package com.example.administrator.xiaoxiang.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.xiaoxiang.R;
import com.example.administrator.xiaoxiang.adapter.BaseTypeAdapter;
import com.example.administrator.xiaoxiang.adapter.BaseViewHolder;
import com.example.administrator.xiaoxiang.adapter.DataHolder;
import com.example.administrator.xiaoxiang.adapter.LayoutWrapper;
import com.example.administrator.xiaoxiang.data.DetailPagesData;
import com.example.administrator.xiaoxiang.data.item_text_data;
import com.example.administrator.xiaoxiang.entity.ShopingcartEntity;
import com.example.administrator.xiaoxiang.gen.DaoMaster;
import com.example.administrator.xiaoxiang.gen.DaoSession;
import com.example.administrator.xiaoxiang.gen.ShopingcartEntityDao;
import com.example.administrator.xiaoxiang.url.URLResource;
import com.example.administrator.xiaoxiang.utils.OkHttpHelper;
import com.example.administrator.xiaoxiang.utils.ShareSDKUtils;
import com.example.administrator.xiaoxiang.utils.SpotsCallBack;
import com.google.gson.Gson;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

public class DetailPagesActivity extends Activity {
    private String path;
    private OkHttpHelper mOkHttpHelper = OkHttpHelper.getInstance();
    private RecyclerView mRecyclerView;
    private BaseTypeAdapter mBaseTypeAdapter;
    private Toolbar mToolbar;
    private TextView detail_page_tv;
    private int mDistanceY;
    private DetailPagesData detailPagesData;
    private ShopingcartEntityDao shopingcartEntityDao;
    private int count = 0;
    private TextView count_textView;
    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_pages);
        Intent intent = getIntent();
        String getGoodsCode = intent.getStringExtra("getGoodsCode");
        path = URLResource.DetailPageURL +  getGoodsCode+ ".json";
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_DetailPages);
        mToolbar= (Toolbar) findViewById(R.id.toolbar_detail);
        detail_page_tv= (TextView) findViewById(R.id.detail_page_tv);
        count_textView = (TextView) findViewById(R.id.circle);
        mTextView= (TextView) findViewById(R.id.detail_page_tv);

        init();

    }

    private void init() {
        mOkHttpHelper.get(path, new SpotsCallBack(this) {
            @Override
            public void onSuccess(String response) {
                Gson gson = new Gson();
                detailPagesData = gson.fromJson(response, DetailPagesData.class);
                String pice;
                if (detailPagesData.getBody() != null) {
                    pice= detailPagesData.getBody().getGood().getSuperRebateAmount()+"";
                }else{
                    finish();
                    return;
                }
                if (!pice.equals("0")) {
                    detail_page_tv.setText("赚¥" + pice.substring(0, pice.length() - 2));
                }
                int[] layoutId = {R.layout.detail_upitem,R.layout.attributes_item,R.layout.detail_item_text,R.layout.datail_item_image,R.layout.detail_downitem};
                mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
                mBaseTypeAdapter = new BaseTypeAdapter(DetailPagesActivity.this, layoutId);
                mRecyclerView.setAdapter(mBaseTypeAdapter);
                DataHolder<DetailPagesData.BodyBean> bodyBeanDataHolder = new DataHolder<DetailPagesData.BodyBean>() {
                    @Override
                    public void bind(Context context, BaseViewHolder holder, DetailPagesData.BodyBean item, int postion) {
                        ImageView ivIcon = holder.getImageView(R.id.detailPages_up_image);
                        ImageView come = holder.getImageView(R.id.detailPages_up_come);
                        TextView tvName = holder.getTextView(R.id.detailPages_up_title);
                        TextView detailPages_up_DaZhe = holder.getTextView(R.id.detailPages_up_DaZhe);
                        TextView originalCost = holder.getTextView(R.id.detailPages_up_All);
                        originalCost.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//删除线xian
                        TextView jian = holder.getTextView(R.id.detailPages_up_lijian);
                        TextView namecome = holder.getTextView(R.id.detailPages_up_namecome);
                        Picasso.with(context).load(item.getGood().getThumbnailUrl()).config(Bitmap.Config.RGB_565).resize(dp2px(250),dp2px(250)).into(ivIcon);
                        Picasso.with(context).load(item.getGood().getSourcePlatformPicurl()).config(Bitmap.Config.RGB_565).into(come);
                        tvName.setText(item.getGood().getGoodsName());
                        originalCost.setText(item.getGood().getOriginalPrice() + "");
                        jian.setText("直付立减" + item.getGood().getDirectPaymentAmount());
                        namecome.setText("商家名称：" + item.getGood().getGoodsSourceStoreName());
                        String pice1=item.getGood().getPeroidInstalmentAmount()/100+"";
                        String pice2=item.getGood().getPeroidInstalmentAmount()%100+"";

                        detailPages_up_DaZhe.setText(pice1+"."+pice2+"x"+"12期");
                    }
                };
                DataHolder<DetailPagesData.BodyBean.GoodBean.PropertyValuesBean> propertyValuesBeanDataHolder=new DataHolder<DetailPagesData.BodyBean.GoodBean.PropertyValuesBean>() {
                    @Override
                    public void bind(Context context, BaseViewHolder holder, DetailPagesData.BodyBean.GoodBean.PropertyValuesBean item, int postion) {
                        TextView attributes_tv1 = holder.getTextView(R.id.attributes_tv1);
                        TextView attributes_tv2 = holder.getTextView(R.id.attributes_tv2);
                        attributes_tv1.setText("·"+item.getProperty().getName()+":");
                        attributes_tv2.setText(item.getOption().getPropertyOptionsValue());
                    }
                };
                DataHolder<item_text_data> item_text_dataDataHolder=new DataHolder<item_text_data>() {
                    @Override
                    public void bind(Context context, BaseViewHolder holder, item_text_data item, int postion) {
                        TextView detail_item_text = holder.getTextView(R.id.detail_item_text);
                        detail_item_text.setText(item.getTitle());
                    }
                };
                DataHolder<DetailPagesData.BodyBean.GoodBean.ImagesBean> imagesBeanDataHolder=new DataHolder<DetailPagesData.BodyBean.GoodBean.ImagesBean>() {
                    @Override
                    public void bind(Context context, BaseViewHolder holder, DetailPagesData.BodyBean.GoodBean.ImagesBean item, int postion) {

                        ImageView detail_item_image = holder.getImageView(R.id.detail_item_image);
                        Picasso.with(context).load(item.getImageUrl()).resize(dp2px(250),dp2px(250)).config(Bitmap.Config.RGB_565).into(detail_item_image);

                    }
                };
                DataHolder<DetailPagesData.BodyBean.GoodBean.BrandBean> brandBeanDataHolder=new DataHolder<DetailPagesData.BodyBean.GoodBean.BrandBean>() {
                    @Override
                    public void bind(Context context, BaseViewHolder holder, DetailPagesData.BodyBean.GoodBean.BrandBean item, int postion) {
                        ImageView iv_rebata_down = holder.getImageView(R.id.iv_rebata_down);
                        Picasso.with(context).load(item.getLogo()).config(Bitmap.Config.RGB_565).into(iv_rebata_down);
                        TextView tv_rebata_down = holder.getTextView(R.id.tv_rebata_down);
                        tv_rebata_down.setText(item.getIntroduce());
                    }
                };
                List<LayoutWrapper> data = new ArrayList<LayoutWrapper>();
                data.add(new LayoutWrapper(R.layout.detail_upitem, detailPagesData.getBody(), bodyBeanDataHolder));
                for (int i = 0; i< detailPagesData.getBody().getGood().getPropertyValues().size(); i++) {
                    data.add(new LayoutWrapper(R.layout.attributes_item, detailPagesData.getBody().getGood().getPropertyValues().get(i),propertyValuesBeanDataHolder));
                }
                data.add(new LayoutWrapper(R.layout.detail_item_text, new item_text_data("商品详情"), item_text_dataDataHolder));

                for (int i = 0; i< detailPagesData.getBody().getGood().getImages().size(); i++) {
                    data.add(new LayoutWrapper(R.layout.datail_item_image, detailPagesData.getBody().getGood().getImages().get(i),imagesBeanDataHolder));
                }
                data.add(new LayoutWrapper(R.layout.detail_downitem, detailPagesData.getBody().getGood().getBrand(), brandBeanDataHolder));
                mBaseTypeAdapter.setData(data);

            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }
        });
    }

    private void initDb(DetailPagesData detailPagesData) {
        ShopingcartEntity shopingcartEntity = new ShopingcartEntity();
        shopingcartEntity.set_id(Long.parseLong(detailPagesData.getBody().getGood().getGoodsCode()));
        shopingcartEntity.setPhotoUrl(detailPagesData.getBody().getGood().getThumbnailUrl());
        shopingcartEntity.setPrice_old(detailPagesData.getBody().getGood().getPromotionPrice()/100.0+"");
        shopingcartEntity.setPrice_new(detailPagesData.getBody().getGood().getPeroidInstalmentAmount()/100.0+"");
        shopingcartEntity.setTitle(detailPagesData.getBody().getGood().getTitle());
        shopingcartEntity.setCount(detailPagesData.getBody().getGood().getInstalmentPeriods()+"");
        ShopingcartEntity shopingcartEntity1 = shopingcartEntityDao.queryBuilder().where(ShopingcartEntityDao.Properties._id.eq(Long.parseLong(detailPagesData.getBody().getGood().getGoodsCode())))
                .build().unique();
//        QueryBuilder<ShopingcartEntity> shopingcartEntityQueryBuilder = shopingcartEntityDao.queryBuilder();
        if (shopingcartEntity1!=null) {
            int num = Integer.parseInt(shopingcartEntity1.getNum());
            num++;
            Log.e("YY", "initDb: "+num);
            shopingcartEntity1.setNum(num+"");
            shopingcartEntityDao.update(shopingcartEntity1);
        }else{
            shopingcartEntity.setNum(1+"");
            shopingcartEntityDao.insert(shopingcartEntity);
        }
    }

    private void initDb() {
        DaoMaster.DevOpenHelper openHelper = new DaoMaster.DevOpenHelper(getApplicationContext(), "XX.db", null);
        SQLiteDatabase db = openHelper.getReadableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
        shopingcartEntityDao = daoSession.getShopingcartEntityDao();
        List<ShopingcartEntity> list =
                shopingcartEntityDao.queryBuilder().build().list();
        for (ShopingcartEntity shopingcartEntity : list) {
            count+=Integer.parseInt(shopingcartEntity.getNum());
        }
    }

    /**
     * dp2px
     */
    public int dp2px(float dpValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public void click(View view) {
        switch (view.getId()){
            case R.id.shop_cart:
                Intent intent = new Intent(this,ShopCardActivity.class);
                startActivity(intent);
                break;
            case R.id.text_shopping:
                if (detailPagesData != null) {
                    initDb(detailPagesData);//对数据库进行操作
                    Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
                    count++;
                    count_textView.setVisibility(View.VISIBLE);
                    count_textView.setText(count +"");
                }else{
                    Toast.makeText(this, "请稍等。。", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.text_shopping2:
                break;
            case R.id.iv_back:
                finish();
                break;

            case R.id.detail_page_tv:
                ShareSDKUtils.showShare(this,"","","");

               // Toast.makeText(DetailPagesActivity.this,"可点击",Toast.LENGTH_SHORT).show();
//                OnekeyShare oks1 = new OnekeyShare();
//                //关闭sso授权
//                oks1.disableSSOWhenAuthorize();
//                // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
//                //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
//                // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
//                oks1.setTitle(detailPagesData.getBody().getGood().getGoodsName());
//                // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
//                oks1.setTitleUrl("http://sharesdk.cn");
//                // text是分享文本，所有平台都需要这个字段
//                oks1.setText("我是分享文本");
//                //要分享图片的话   确保图片存在   如果图片不存在  分享失败
//                oks1.setImageUrl(detailPagesData.getBody().getGood().getThumbnailUrl());
//                // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//                //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
//                // url仅在微信（包括好友和朋友圈）中使用
//                oks1.setUrl(detailPagesData.getBody().getGood().getThumbnailUrl());
//                // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//                oks1.setComment("我是测试评论文本");
//                // site是分享此内容的网站名称，仅在QQ空间使用
//                //   oks.setSite(getString(R.string.app_name));
//                // siteUrl是分享此内容的网站地址，仅在QQ空间使用
//                oks1.setSiteUrl("http://sharesdk.cn");
//                // 启动分享GUI
//                oks1.show(getApplicationContext());
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        count = 0;
        initDb();
        if (count ==0) {
            count_textView.setVisibility(View.GONE);
        }else{
            count_textView.setVisibility(View.VISIBLE);
            count_textView.setText(count +"");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    setContentView(R.layout.view_null);
    }
}
